{% extends "base.html" %}

{% block content %}
<div class="container mt-4">
    <div class="row">
        <!-- 温度图表 -->
        <div class="col-12 mb-4">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h5 class="card-title mb-0">温度变化趋势</h5>
                </div>
                <div class="card-body">
                    <div class="chart-box" id="temperatureChart">
                        <canvas></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- 湿度图表 -->
        <div class="col-12 mb-4">
            <div class="card">
                <div class="card-header bg-info text-white">
                    <h5 class="card-title mb-0">湿度变化趋势</h5>
                </div>
                <div class="card-body">
                    <div class="chart-box" id="humidityChart">
                        <canvas></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- 城市对比图表 -->
        <div class="col-12 mb-4">
            <div class="card">
                <div class="card-header bg-success text-white">
                    <h5 class="card-title mb-0">城市天气对比</h5>
                </div>
                <div class="card-body">
                    <div class="chart-box" id="cityComparisonChart">
                        <canvas></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
.chart-box {
    position: relative;
    height: 400px;
    width: 100%;
    margin: 10px 0;
}

.loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #666;
}

.error {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    color: #dc3545;
}

canvas {
    width: 100% !important;
    height: 100% !important;
}
</style>

<script>
function loadAndCreateCharts() {
    console.log("开始加载图表数据...");
    
    // 显示加载状态
    document.querySelectorAll('.chart-box').forEach(box => {
        box.innerHTML = '<div class="loading">数据加载中...</div>';
    });

    fetch('/api/weather/current')
        .then(response => response.json())
        .then(data => {
            console.log("获取到的数据:", data);
            
            if (data.status === 'success' && data.data && data.data.length > 0) {
                // 按城市分组数据
                const cityData = {};
                data.data.forEach(item => {
                    if (!cityData[item.location]) {
                        cityData[item.location] = [];
                    }
                    cityData[item.location].push(item);
                });

                // 创建温度图表
                const tempCtx = document.getElementById('temperatureChart');
                if (tempCtx) {
                    tempCtx.innerHTML = '<canvas></canvas>';
                    createTemperatureChart(cityData, tempCtx.querySelector('canvas'));
                }

                // 创建湿度图表
                const humidityCtx = document.getElementById('humidityChart');
                if (humidityCtx) {
                    humidityCtx.innerHTML = '<canvas></canvas>';
                    createHumidityChart(cityData, humidityCtx.querySelector('canvas'));
                }

                // 创建城市比较图表
                const comparisonCtx = document.getElementById('cityComparisonChart');
                if (comparisonCtx) {
                    comparisonCtx.innerHTML = '<canvas></canvas>';
                    createCityComparisonChart(cityData, comparisonCtx.querySelector('canvas'));
                }
            } else {
                document.querySelectorAll('.chart-box').forEach(box => {
                    box.innerHTML = '<div class="error">暂无数据</div>';
                });
            }
        })
        .catch(error => {
            console.error('加载数据失败:', error);
            document.querySelectorAll('.chart-box').forEach(box => {
                box.innerHTML = '<div class="error">加载失败</div>';
            });
        });
}

function createTemperatureChart(cityData, canvas) {
    const cities = Object.keys(cityData);
    const datasets = cities.map(city => ({
        label: city,
        data: cityData[city].map(d => d.temperature),
        borderColor: getRandomColor(),
        fill: false
    }));

    new Chart(canvas, {
        type: 'line',
        data: {
            labels: cityData[cities[0]].map(d => 
                new Date(d.date_time).toLocaleTimeString()),
            datasets: datasets
        },
        options: {
            responsive: true,
            plugins: {
                title: {
                    display: true,
                    text: '各城市温度变化'
                }
            },
            scales: {
                y: {
                    beginAtZero: false,
                    title: {
                        display: true,
                        text: '温度 (°C)'
                    }
                }
            }
        }
    });
}

function createHumidityChart(cityData, canvas) {
    const cities = Object.keys(cityData);
    const datasets = cities.map(city => ({
        label: city,
        data: cityData[city].map(d => d.humidity),
        borderColor: getRandomColor(),
        fill: false
    }));

    new Chart(canvas, {
        type: 'line',
        data: {
            labels: cityData[cities[0]].map(d => 
                new Date(d.date_time).toLocaleTimeString()),
            datasets: datasets
        },
        options: {
            responsive: true,
            plugins: {
                title: {
                    display: true,
                    text: '各城市湿度变化'
                }
            },
            scales: {
                y: {
                    beginAtZero: true,
                    title: {
                        display: true,
                        text: '湿度 (%)'
                    }
                }
            }
        }
    });
}

function createCityComparisonChart(cityData, canvas) {
    const cities = Object.keys(cityData);
    const latestData = cities.map(city => ({
        city: city,
        temp: cityData[city][0].temperature,
        humidity: cityData[city][0].humidity
    }));

    new Chart(canvas, {
        type: 'bar',
        data: {
            labels: cities,
            datasets: [
                {
                    label: '温度',
                    data: latestData.map(d => d.temp),
                    backgroundColor: 'rgba(255, 99, 132, 0.5)',
                    yAxisID: 'y'
                },
                {
                    label: '湿度',
                    data: latestData.map(d => d.humidity),
                    backgroundColor: 'rgba(54, 162, 235, 0.5)',
                    yAxisID: 'y1'
                }
            ]
        },
        options: {
            responsive: true,
            plugins: {
                title: {
                    display: true,
                    text: '城市天气对比'
                }
            },
            scales: {
                y: {
                    type: 'linear',
                    position: 'left',
                    title: {
                        display: true,
                        text: '温度 (°C)'
                    }
                },
                y1: {
                    type: 'linear',
                    position: 'right',
                    title: {
                        display: true,
                        text: '湿度 (%)'
                    }
                }
            }
        }
    });
}

function getRandomColor() {
    const letters = '0123456789ABCDEF';
    let color = '#';
    for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
}

// 页面加载完成后初始化图表
document.addEventListener('DOMContentLoaded', function() {
    console.log("页面加载完成，开始初始化图表...");
    loadAndCreateCharts();
});
</script>
{% endblock %} 